/**
 * @company : 版权所属 四川北星惯牌科技有限公司
 * @contact : 刘经理 19326416371
 **/
/* 
 支付
 */

/* 
 页面内使用
 import { usePay } from '@/hooks/usePay.js'
 const { weixinH5Pay, appPay } = usePay()
 
 // 微信H5调起微信支付

 
 // APP、小程序支付
 // orderInfo 订单数据
 // provider  服务供应商

 */

const usePay = () => {
	/**
	 * @description 微信H5调起微信支付
	 * @param {object} wxJsApiParam 微信支付验证参数(后台接口调用微信商家支付平台回调)
	 */
	const weixinH5Pay = (wxJsApiParam, callback, errorCallback) => {
		// 内部函数
		const jsApiCall = (jsPara) => {
			WeixinJSBridge.invoke(
				'getBrandWCPayRequest', {
					"appId": jsPara.appId,
					"nonceStr": jsPara.nonceStr,
					"package": jsPara.package,
					"paySign": jsPara.paySign,
					"signType": jsPara.signType,
					"timeStamp": jsPara.timeStamp
				}, (res) => {
					if (res.err_msg == "get_brand_wcpay_request:ok") {
						// 支付成功
						callback && callback('支付成功')
					} else if (res.err_msg == "get_brand_wcpay_request:cancel") {
						// 取消支付
						errorCallback && errorCallback('取消支付')
					} else {
						// 支付失败
						errorCallback && errorCallback('支付失败')
					}
				}
			)
		}
		// 方法内代码 --- 开始
		if (typeof WeixinJSBridge == "undefined") {
			if (document.addEventListener) {
				document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
			} else if (document.attachEvent) {
				document.attachEvent('WeixinJSBridgeReady', jsApiCall);
				document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
			}
		} else {
			jsApiCall(wxJsApiParam, orderCodePay)
		}
	}

	/* 
	 小程序封装
	 */
	const appPay = (orderInfo, provider) => {
		return new Promise((resolve, reject) => {
			// 获取服务供应商
			uni.getProvider({
				service: "payment",
				success: (res) => {
					let providerInfo = provider || res.provider
					let order = orderInfo;
					uni.requestPayment({
						provider: providerInfo,
						timeStamp: order.timeStamp,
						nonceStr: order.nonceStr,
						package: order.package,
						signType: order.signType,
						paySign: order.paySign,
						success: (res) => {
							resolve({
								code: 200,
								msg: '支付成功',
								data: res
							})
						},
						fail: (res) => {
							console.log('fail', res);
							if (res.errMsg === 'requestPayment:fail cancel') {
								resolve({
									code: 100,
									msg: '取消支付',
									data: res
								})
							} else {
								reject('支付失败')
							}
						}
					})
				},
				fail: (res) => {
					reject('获取服务供应商失败')
				}
			})
		})
	}
	const getOpenId = () => {
		uni.login({
			provider: 'weixin', //使用微信code
			success: async (loginRes) => {
				console.log(loginRes);
				if (loginRes.code) {
					return
					const res = await $Api.login.getOpenId({
						code: loginRes.code
					})
					if (res.code == '1') {
					} else {
						uni.$u.toast(res.msg);
					}
				}

			}
		});
	}
	return {
		weixinH5Pay,
		appPay
	}
}

export {
	usePay
}